package org.tity.commons.environment;

 
import java.io.UnsupportedEncodingException;
import java.net.URL;

import org.tity.commons.io.EasyFile;
import org.tity.commons.lang.StringUtil;

 
/**
 * @author fangjieli 
 * */
public class PathTool {
	 
	/**
	 * 获得类所在的目录
	 * @param cls  类
	 * @return 类所在的目录
	 * */
	public static EasyFile getDir(Class cls)
	{
		return new EasyFile(getPath(cls));
	}
	
	/**
	 * 获得类所在的路径
	 * @param cls  类
	 * @return 类所在的路径
	 * */
	public static String getPath(Class cls) {
		String strURL="";
		try{
		String strClassName = cls.getName();
		String strPackageName = "";
		if (cls.getPackage() != null) {
			strPackageName = cls.getPackage().getName();
		}

		String strClassFileName = "";
		if (!"".equals(strPackageName)) {
			strClassFileName = strClassName.substring(
					strPackageName.length() + 1, strClassName.length());
		} else {
			strClassFileName = strClassName;
		}

		URL url = null;
		url = cls.getResource(strClassFileName + ".class");
		strURL = url.toString();
		strURL = strURL.substring(strURL.indexOf('/') + 1, strURL
				.lastIndexOf('/'));

		try {
			strURL = java.net.URLDecoder.decode(strURL, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		OSType os = OSType.getOSType(); 
		if (os == OSType.WINDOWS) {

		} else if (os == OSType.LINUX) {
			strURL = "/" + strURL;
		} else if (os == OSType.MAC) {
			strURL = "/" + strURL;
		}
		} catch(Exception c)
		{

		}
		return strURL;
	}

	/**
	 * 通过相对路径获得页面的绝对路径
	 * @param  relativePath 相对路径
	 * @return  绝对路径
	 * */
	public static String getRealPathInWebApp(String relativePath) {
		String path = PathTool.getPath(PathTool.class);
		path = path.substring(0, path.indexOf("/WEB-INF/"));
		return path + "/" + relativePath;
	}
	
	
	private static final String JAR_KEY=".jar!/";
	private static final String FILE_KEY="file:/";
	
	/**
	 * 获得启动目录，即输入启动命令的路径
	 * @return 当前工作目录
	 * */
	public static EasyFile getWorkDir()
	{
		return new EasyFile(".");
	}
	/**
	 * 获得当前执行的Jar所在目录
	 * 如果是jar启动则获得jar文件所在的目录
	 * 如果是class文件启动则返回classes根目录
	 * @return  启动目录
	 * */
	public static EasyFile getBootJarDir()
	{
		String path = PathTool.class.getProtectionDomain().getCodeSource().getLocation().getPath();
		if(StringUtil.isEmpty(path)) {
			return null;
		}
		int i=path.toLowerCase().indexOf(JAR_KEY);
		if(i!=-1)
		{
				path=path.substring(0, i);
				i=path.lastIndexOf("/");
				path=path.substring(0, i);
		}
	 
		if(path.startsWith(FILE_KEY))
		{
			path=path.substring(5);
		}
		
		return new EasyFile(path);
		
	}
	
	
	
	
	
}
